package com.opages.mvc.common.config;

import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

public class OpagesWebMvcConfiguration {

    // 扩展AdqRequestMappingHandlerMapping，解决OpenFeign和RequestMapping加载的问题
    private RequestMappingHandlerMapping requestMappingHandlerMapping = new OpagesWebMvcConfiguration.FeignRequestMappingHandlerMapping();
    //此处需注意，如果不使用全路径名无法覆盖原先spring注入的对象，导致FeignClient与RequestMapping出现冲突现象
    @Bean("org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping")
    public RequestMappingHandlerMapping requestMappingHandlerMapping() {
        return requestMappingHandlerMapping;
    }

    /**
     * 解决@FeignClient与@RequestMapping同时注解出错问题
     * @Author daizhong.liu
     * @Date 2020/9/9 11:50
     **/
    private static class FeignRequestMappingHandlerMapping extends RequestMappingHandlerMapping {
        @Override
        protected boolean isHandler(Class<?> beanType) {
            // 判断不是Feign注解的API类，且Controller必须注解了Controller或继承了BaseController父类
            return super.isHandler(beanType) &&
                    (!AnnotatedElementUtils.hasAnnotation(beanType, FeignClient.class)
                    || AnnotatedElementUtils.hasAnnotation(beanType, Controller.class));
        }
    }
}
